import React, { useImperativeHandle, useState,useRef } from 'react'
import { Form, Input, Button, Modal, message } from 'antd';
import axios from 'axios'

export default function AddUser(props) {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const formRef = useRef()
  //用useImperativeHandle暴露一些外部ref能访问的属性
  useImperativeHandle(props.onRef, () => {
    return {
      setIsModalVisible
    };
  });
  //关闭添加用户
  const handleCancel = () => {
    setIsModalVisible(false);
  }

  // 提交添加用户表单成功
  const onFinish = async (values) => {
    console.log('Success:', values);
    const { username, password } = values
    const role = 1
    const { data } = await axios.post('/api/v1/user/add', { username, password, role })
    console.log(data);
    if (data.status === 200) {
      message.success('添加用户成功');
      setIsModalVisible(false);
      formRef.current.resetFields()
    }
    else {
      message.error(data.message);
      formRef.current.resetFields()
    }
  };
  // 提交添加用户表单失败
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <Modal footer={null} title="添加用户" visible={isModalVisible} onCancel={handleCancel} >
      <Form
        ref={formRef}
        name="addUser"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        initialValues={{}}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 4, max: 14, message: '用户名长度在4~14个字符之间' }
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 6, max: 20, message: '密码长度在6~20个字符之间' }
          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item
          label="确认密码"
          name="passwordAgain"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 6, max: 20, message: '密码长度在6~20个字符之间' },
            //两次密码比较验证
            ({getFieldValue})=>({
              validator(rule,value){
                if(!value || getFieldValue('password') === value){
                  return Promise.resolve()
                }
                return Promise.reject("两次密码输入不一致")
              }
            })

          ]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            添加用户
          </Button>
        </Form.Item>
      </Form>
    </Modal>

  )
}
